﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace EpubFactory.Common
{

    public interface IBookFileCreator
    {
        void Generate(Book book, string targetFile);
    }
    public abstract class BookFileCreator : IBookFileCreator
    {
        static Regex _htmlRegex = new Regex("<.*?>", RegexOptions.Compiled);
        public abstract void Generate(Book book, string targetFile);
        public virtual void DeleteFile(string path)
        {
            if (File.Exists(path))
            {
                File.Delete(path);
            }
        }
        public virtual void CreateTempDir(string path)
        {
            var dir = Path.GetDirectoryName(path);
            var fileName = Path.GetFileNameWithoutExtension(path);
            var tmpDir = Path.Combine(dir, fileName + "-tmp");
            if (Directory.Exists(tmpDir))
            {
                Directory.Delete(tmpDir, true);
            }
            Directory.CreateDirectory(tmpDir);
        }
        public virtual void GenerateBookChaptersId(Book book)
        {
            if (!book.FlattedChapters.Any(d => string.IsNullOrWhiteSpace(d.Id)))
            {
                return;
            }
            book.GenerateChaptersId();
        }

        public virtual string StripTags(string html, string allowableTags = null)
        {
            return _htmlRegex.Replace(html, string.Empty);
        }
    }
    public abstract class TemplateCreator : BookFileCreator
    {
        public string TemplateFile { get; set; }
        public string TempDir { get; set; }
        public TemplateCreator()
        {
            this.TempDir = AppPreference.Load().TempDir;
        }
        public virtual string CreateTempDir(Book book)
        {
            var tmpDir = Path.Combine(TempDir, book.EPubId);
            if (Directory.Exists(tmpDir))
            {
                Directory.Delete(tmpDir, true);
            }
            Directory.CreateDirectory(tmpDir);
            return TempDir;
        }
    }


    public class TxtCreator : BookFileCreator
    {
        public override void Generate(Book book, string targetFile)
        {
            DeleteFile(targetFile);
            File.WriteAllText(targetFile, string.Join("\n", book.Chapters.Select(g => string.Format("{0}\n{1}", g.Title, g.Content))));
        }
    }

}
